package com.xxxx.oa.web.action;

import com.xxxx.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet("/welcome")
public class WelcomServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        String loginName = null;
        String loginPwd = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("loginName".equals(name)) {
                    loginName = cookie.getValue();
                } else if ("loginPwd".equals(name)) {
                    loginPwd = cookie.getValue();
                }
            }
        }
        if(loginName!=null&&loginPwd!=null){
            Connection conn=null;
            PreparedStatement ps=null;
            ResultSet rs=null;
            boolean isflag=false;
            try {
                conn = DBUtil.getConnection();
                String sql="select * from t_user where loginName = ? and loginPwd = ?";
                ps=conn.prepareStatement(sql);
                ps.setString(1,loginName);
                ps.setString(2,loginPwd);
                rs=ps.executeQuery();
                if(rs.next()){
                    isflag=true;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                DBUtil.close(conn,ps,rs);
            }
            if(isflag){
                HttpSession session = request.getSession();
                session.setAttribute("loginName",loginName);
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }else{
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
        }else{
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }
}
